﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.IO;
using System.Net;
using System.Collections;
using System.Runtime.InteropServices;
using Microsoft.Win32;

namespace Ease_Proxy_Switch
{
    public partial class EPS : Form
    {
        [DllImport("wininet.dll")]
        public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
        public const int INTERNET_OPTION_SETTINGS_CHANGED = 39;
        public const int INTERNET_OPTION_REFRESH = 37;
        static bool settingsReturn, refreshReturn;

        public EPS()
        {
            InitializeComponent();
        }
        //Buttons on the Forms
        private void doneButton_Click(object sender, EventArgs e)
        {
            string[] proxyList = (proxyTextBox.Text).Split(new string[]{"\r\n"},StringSplitOptions.None);
            foreach (string c in proxyList)
                proxyListBox.Items.Add(c);
            proxyTextBox.Text = "";
        }

        private void removeButton_Click(object sender, EventArgs e)
        {
            proxyListBox.Items.Remove(proxyListBox.SelectedItem);
        }

        private void startButton_Click(object sender, EventArgs e)
        {
            if (proxyListBox.SelectedItem != null)
            {
                string proxy = proxyListBox.SelectedItem.ToString();
                string[] spilt = proxy.Split(new char[]{' ',':',','}, StringSplitOptions.RemoveEmptyEntries);
                ipLabel.Text = "Proxy IP: " + spilt[0];
                portLabel.Text = "Port: " + spilt[1];
                string comProxy = spilt[0] + ":" + spilt[1];
                ipLabel.Visible = true;
                portLabel.Visible = true;

                RegistryKey reg = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
                reg.SetValue("ProxyEnable", 1);
                reg.SetValue("ProxyServer", comProxy);
                settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
                refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
            }
            else
                MessageBox.Show("Please select a proxy from the list", "No proxy is selected", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void disableButton_Click(object sender, EventArgs e)
        {
            portLabel.Visible = false;
            ipLabel.Visible = true;
            ipLabel.Text = "Proxy Switched Off";
            RegistryKey reg = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
            reg.SetValue("ProxyEnable", 0);
            settingsReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
            refreshReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
        }
        //
        //Toolstrip1 - "File"
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(proxyListBox.Items.Count != 0)
                proxyListBox.Items.Clear();
            DialogResult openFile = openFileDialog1.ShowDialog();
            if (openFile == DialogResult.OK)
            {
                StreamReader readFile = new StreamReader(openFileDialog1.FileName);
                while (readFile.Peek() != -1)
                {
                     proxyListBox.Items.Add(readFile.ReadLine());
                }
                proxyListBox.Items.Remove("#Save File Generated by EPS");
                readFile.Close();
                tabControl1.SelectTab(1);
            }
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string name = openFileDialog1.FileName;
            if (name == "openFileDialog1")
            {
                name = "Proxy.txt";
            }
            saveFunction(name);
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveFileDialog1.ShowDialog();
        }

        private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            string name = saveFileDialog1.FileName;
            saveFunction(name);
        }

        private void saveFunction(string name) 
        {
            string[] proxyList = new string[proxyListBox.Items.Count + 1];
            proxyList[0] = "#Save File Generated by EPS";
            for (int i = 1; i < proxyList.Length; i++)
                proxyList[i] = proxyListBox.Items[i - 1].ToString();
            File.WriteAllLines(name, proxyList);
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        //
        //Toolstrip1 - "Edit"
        private void removeAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            proxyListBox.Items.Clear();
        }
        //
        //Proxy Status Checker
        private void checkProxyStatusToolStripMenuItem_Click(object sender, EventArgs e)
        {
            checkProxy();
        }

        private void checkButton_Click(object sender, EventArgs e)
        {
            checkProxy();
        }

        private void checkProxy()
        {
            tbProgress.Text = "Verifying Proxies...";
            startButton.Enabled = false;
            checkProgressBar.Maximum = proxyListBox.Items.Count;
            if (backgroundWorker1.IsBusy != true)
                backgroundWorker1.RunWorkerAsync();
        }
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            int count = 1;
            bool status;
            string[] proxyList = new string[proxyListBox.Items.Count];
            proxyListBox.Items.CopyTo(proxyList, 0);
            foreach (string proxy in proxyList)
            {
                status = checkProxy(proxy);
                if (status == false)
                    RemoveListBoxItem(proxy);
                backgroundWorker1.ReportProgress(count++);
            }
        }
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                // There was an error during the operation.
                MessageBox.Show("Error", "Not Completed", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                // The operation completed normally.
                MessageBox.Show("Completed", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
                startButton.Enabled = true;
                tbProgress.Text = proxyListBox.Items.Count.ToString() + " Online";
            }
        }
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            tbProgress.Text = "Verifying... " +e.ProgressPercentage.ToString() + " Checked";
            checkProgressBar.Value++;
        }
        private bool checkProxy(string proxy)
        {
            try
            {
                string[] spilt = proxy.Split(new char[] { ' ', ':', ',' }, StringSplitOptions.RemoveEmptyEntries);
                WebRequest checker = WebRequest.Create("http://www.google.com");
                checker.Proxy = new WebProxy(spilt[0], Int32.Parse(spilt[1]));
                checker.Timeout = 13000;
                checker.GetResponse();
                return true;
            }
            catch
            {
                return false;
            }
        }
        private delegate void RemoveListBoxItemDelegate(object item);
        private void RemoveListBoxItem(object item)
        {
            if (this.proxyListBox.InvokeRequired)
                // This is a worker thread so delegate the task.
                this.proxyListBox.Invoke(new RemoveListBoxItemDelegate(this.RemoveListBoxItem), item);
            else
                // This is the UI thread so perform the task.
                this.proxyListBox.Items.Remove(item);
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Project links hosted by codeplex. http://easeps.codeplex.com/documentation" ,"Information",MessageBoxButtons.OK,MessageBoxIcon.Information);
        }
        //
    }
}
